<script lang="ts" setup>
import { reactive, ref, watch, toRefs } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
// 接口
import { getBonusList, addBonust, updateBonust, delBonust } from "@/api/SZ/bonus"
import { getqueryTeamName } from "@/api/SZ/SZXxfy"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "SZBouns"
})
const DATA = reactive<any>({
  formData: { details: "" }
})
const { formData } = toRefs(DATA)
const shopList = ref<any>([])
const formRef = ref<FormInstance | null>(null)
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  shopId: [{ required: true, message: "请选择店铺", trigger: "blur" }],
  executionTime: [{ required: true, message: "请选择执行日期", trigger: "blur" }],
  perCardBonus: [{ required: true, message: "请填写单卡奖金", trigger: "blur" }]
})
/**店铺数据 */
const getShopList = () => {
  getqueryTeamName().then((res: any) => {
    if (res.code == 200) {
      shopList.value = res.data
      // console.log(res)
    }
  })
}
getShopList()
const addProduct = () => {
  dialogVisible.value = true
  resetForm()
  formData.value = {}
}

// #region 改
const teamId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  teamId.value = row.id
  formData.value = JSON.parse(JSON.stringify(row))
  formData.value.shopId = {
    id: Number(row.shopId),
    name: row.shopName
  }
  dialogVisible.value = true
}
// #endregion

// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除ID为:${row.id}的数据吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delBonust({
      id: row.id,
      manageName: row.manageName
    }).then(() => {
      ElMessage.success("删除成功")
      getList()
    })
  })
}
// #endregion

// #region 增
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (teamId.value === undefined) {
        addBonust({
          ...formData.value,
          shopId: formData.value.shopId.id,
          shopName: formData.value.shopId.name
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getList()
        })
      } else {
        updateBonust({
          ...formData.value,
          shopId: formData.value.shopId.id,
          shopName: formData.value.shopId.name
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getList()
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  teamId.value = undefined
  formRef.value?.resetFields()

  clearValidate()
}
// #endregion
// #region 查
const tableTotal = ref<number>()
const tableData = ref<any[]>([])
const getList = () => {
  getBonusList({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    ...searchData
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
      loading.value = false
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  shopId: "",
  searchData: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getList()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getList()
    console.log("查询")
  }
  paginationData.currentPage = 1
}

// #endregion
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getList, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="shopId" label="店铺">
          <el-select v-model="searchData.shopId" clearable filterable placeholder="请选择">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="manageName" label="操作人">
          <el-input v-model="searchData.manageName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加职位 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="addProduct">添加</el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column prop="id" label="ID" />
          <el-table-column label="操作时间" align="center" prop="manageTime" />
          <el-table-column prop="manageName" label="操作人" />
          <el-table-column prop="shopName" label="店铺" />
          <el-table-column prop="executionTime" label="执行日期" />
          <el-table-column prop="perCardBonus" label="单卡奖金" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="teamId === undefined ? '新增' : '修改'" @close="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="店铺" prop="shopId" label-width="120">
          <el-select v-model="formData.shopId" clearable filterable placeholder="请选择" value-key="id">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="执行日期" prop="executionTime" label-width="120">
          <el-date-picker v-model="formData.executionTime" type="date" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="单卡奖金" prop="perCardBonus" label-width="120">
          <el-input-number
            :min="0"
            :max="1000"
            :precision="2"
            v-model="formData.perCardBonus"
            type="number"
            placeholder="仅可输入数字金额"
            style="width: 220px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
